#!/usr/bin/python
# -*- coding: utf-8 -*-  
import time
import datetime

# proxy_reportor is a callback function, which can be set by the user,format is time_cost_cb(func_name, time_cost_seconds:float):
proxy_reportor = None
def func_time(func):
    '''
    @summary: cal the time of the fucntion
    @param : None
    @return: return the res of the func
    '''
    def wrapper(*args, **kw):
        start_time = datetime.datetime.now()
        res = func(*args, **kw)
        over_time = datetime.datetime.now()
        if proxy_reportor is not None:
            proxy_reportor(func.__name__, (over_time - start_time).total_seconds())
        else:
            print ('{0} run time is {1}s'.format(func.__name__, (over_time - start_time).total_seconds()))
        return res
    return wrapper
 

class MultiPointTimer:
    '''多点计时器'''
    def __init__(self, name):
        self.name = name
        self.points = []

    def start(self):
        self.points.append(("start", self.current_time_millis()))

    def end(self):
        self.points.append(("end", self.current_time_millis()))

    def probe(self, tip):
        key = tip if tip else "time_{}".format(len(self.points))
        self.points.append((key, self.current_time_millis()))

    def reset(self):
        self.points.clear()

    def summary(self):
        summary = ["MultiPointTimer\t{}".format(self.name)]
        if len(self.points) > 1:
            if len(self.points) > 2:
                summary.append("--------------")
                for i in range(1, len(self.points)):
                    duration = self.points[i][1] - self.points[i-1][1]
                    if duration > 1000:
                        summary.append("{}\t:{}s".format(self.points[i][0], float(duration)/1000))
                    else:
                        summary.append("{}\t:{}ms".format(self.points[i][0], duration))
                summary.append("--------------")
            total = self.points[-1][1] - self.points[0][1]
            if total > 1000:
                summary.append("Total\t:{}s".format(float(total)/1000))
            else:
                summary.append("Total\t:{}ms".format(total))
        else:
            summary.append("Insufficient time points")
        return "\n".join(summary)

    @staticmethod
    def current_time_millis():
        return int(round(time.time() * 1000))


if __name__ == '__main__':
    timer = MultiPointTimer(__name__)
    timer.start()
    time.sleep(1)
    timer.probe("sleep 1s")
    time.sleep(2)
    timer.probe("sleep 2s")
    # 这里放置你的代码逻辑和探针
    timer.end()
    print(timer.summary())